﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Msung.Business;
using Msung.Business.IService;
using Msung.Core;
using Msung.Core.Caching;
using Msung.Core.Extensions;
using Msung.Core.Freesql;
using NLog.Extensions.Logging;
using QuestDbService.IService;
using QuestDbService.Service;
using StowayNet;
using Topshelf;
var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
                       .ConfigureHostConfiguration(ConfigureHostConfiguration)
                       .ConfigureServices(ConfigureServices)
                       .ConfigureLogging(ConfigureLogging)
                       .UseDefaultServiceProvider(options => options.ValidateScopes = false)
                       .UseConsoleLifetime()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .Build();

void ConfigureLogging(HostBuilderContext context, ILoggingBuilder loggingBuilder)
{
    loggingBuilder.AddNLog("Configs/nlog.config");
    loggingBuilder.AddConsole();
}

void ConfigureServices(HostBuilderContext hostBuilderContext, IServiceCollection services)
{
    services.AddStowayNet();
    //services.AddAutoMapper(typeof(AutoMapperProfiles));
    //配置文件加载到静态
    services.BuildConfiguration();
    //注入redis服务
    services.AddRedisCache();
    //注入生产者
    services.AddKafkaProducers();
    //注入消费者
    services.AddKafkaConsumers();
    //注入NOSQL数据库
    services.AddMultiNoSqlDB();
    //注入业务服务
    services.AddService();
    //添加日志
    //services.AddLogging();
    services.AddRunExtensions();
}


void ConfigureHostConfiguration(IConfigurationBuilder configurationBuilder)
{
    //作为 Windows Service 运行时，默认情况下，Directory.GetCurrentDirectory() 为 C:\WINDOWS\system32
    Directory.SetCurrentDirectory(AppContext.BaseDirectory);
    configurationBuilder.SetBasePath(Directory.GetCurrentDirectory());
    configurationBuilder.AddJsonFile("Configs/appSettings.json", optional: true, reloadOnChange: true);
}

AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
    var logFactory = host.Services.GetService<ILoggerFactory>();
    var logger = logFactory?.CreateLogger<Program>();
    if (logger != null)
        logger.LogError(e.ExceptionObject as Exception, $"UnhandledException");
    else
        logger.logInfo("Program Error");
};
HostFactory.Run(x =>
{
    x.Service<IHost>(s =>
    {
        s.ConstructUsing(() => host);
        s.WhenStarted(service =>
        {
            service.Start();
        });
        s.WhenStopped(service =>
        {
            service.StopAsync();
        });

    });
    x.SetServiceName(AppSetting.AppName);
    x.SetDisplayName(AppSetting.AppName);
    x.SetDescription(AppSetting.AppName);
    AppSetting.GetService<IMainService>().Exacute();
});






















//using Microsoft.Extensions.Configuration;
//using Microsoft.Extensions.DependencyInjection;
//using Msung.Core;
//using Msung.Core.Extensions;
//using Msung.Core.Kafka;

//KafkaServer kafkaServer = new KafkaServer();
//IConfiguration _configuration= new ConfigurationBuilder()
//            .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true)
//            .Build();

//kafkaServer.Register(services =>
//{
//    services.Init(_configuration);
//    services.RegisterModule();
//    ////注入配置文件
//    //services.AddScoped<IConfiguration>(p => _configuration);

//});
//await kafkaServer.StartAsync();
//{

//    _logger.logInfo($"{AppSetting.GetSettingString("AppName")}");
//    var key = Console.ReadLine();
//}
